from django.shortcuts import render
from django.views import  View
from django_redis import  get_redis_connection
from django.contrib.auth import authenticate
from users.models import User
from django import http
from django.contrib.auth import login,logout
import logging,json,re
from meiduo_mall.utils.views import login_required,LoginRequiredMixin
from celery_tasks.email.tasks import send_verify_email
from django.conf import settings
from . models import Address
from goods.models import SKU
from meiduo_mall.utils.views import LoginRequiredMixin
logger = logging.getLogger('django')

# Create your views here.


class UserBrowseHistory(LoginRequiredMixin,View):

    def get(self,request):

        conn = get_redis_connection('history')

        sku_ids = conn.lrange('history_%s' % request.user.id,0,-1)

        skus = []

        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price
            })

        return http.JsonResponse({
            'code':0,
            'errmsg': 'ok',
            'skus': skus
        })



    def post(self,request):

        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')

        conn = get_redis_connection('history')

        user_id = request.user.id

        # 添加管道
        pl = conn.pipeline()

        # 先去重浏览记录
        pl.lrem('history_%s'% user_id,0,sku_id)

        # 再储存浏览记录
        pl.lpush('history_%s'% user_id,sku_id)

        # 再截取 最多5条

        pl.ltrim('history_%s'% user_id,0,4)

        pl.execute()


        return http.JsonResponse({'code': 0,
                             'errmsg': 'OK'})













class UsernameCountView(View):

    def get(self,request,username):

        try:

            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({"code": 400,"errmsg":"数据查找失败"})

        return http.JsonResponse({"code": 0,"errmsg":"ok","count":count})


class MobileCountView(View):

    def get(self,request,mobile):

        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({"code": 0,"errmsg":"ok","count":count})



class RegisterView(View):

    def post(self,request):

        # 提取注册数据 转字典类型
        dict = json.loads(request.body.decode())

        # 得到数据后 提取数据
        username = dict.get('username')
        password = dict.get('password')
        password2 = dict.get('password2')
        mobile = dict.get('mobile')
        sms_code = dict.get('sms_code')
        allow = dict.get('allow')

        # 校验参数是否都填写 allow 是布尔类型的值 我们单独验证
        if not all([username,password,password2,mobile,sms_code]):
            return http.JsonResponse({"code": 400,"errmsg":"参数缺少"})

        # 全部都填写完毕 我么再单独验证每一项的格式是否正确 用正则匹配
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$',username):
            return http.JsonResponse({"code": 400, "errmsg": "用户名格式错误"})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$',password):
            return http.JsonResponse({"code": 400, "errmsg": "密码格式错误"})


        if password2 != password:
            return http.JsonResponse({"code": 400, "errmsg": "重复输入密码错误"})

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({"code": 400, "errmsg": "手机号格式错误"})

        # sms_code 验证
        # 首先 要连接Redis 提取 库里面的保存的 验证码
        conn = get_redis_connection('verify_code')

        sms_code_server =  conn.get('sms_%s' %sms_code)

        # 如果没有验证码 证明失效不存在
        if not sms_code_server:
            return http.JsonResponse({"code": 400, "errmsg": "验证码过期"})

        # 如果有 判断 客户端和服务端是否一致
        if sms_code != sms_code_server.decode():
            return http.JsonResponse({"code": 400, "errmsg": "验证码输入错误"})

        # 判断是否勾选协议
        if allow != True:
            return http.JsonResponse({"code": 400, "errmsg": "协议没选择"})

        # 全部判断成功后 把用户注册的数据保存到MySQL数据表 存入数据库要进行补抓异常
        try:
            uesr = User.objects.create_user(username=username,password=password,mobile=mobile)
        except Exception as e :
            return http.JsonResponse({"code": 400, "errmsg": "保存数据失败"})

        # 做状态保持  用login Django自带的
        login(request,uesr)

        # 设置cookie 前端把用户名加载到 页面
        respones = http.JsonResponse({"code": 0, "errmsg": "ok"})

        respones.set_cookie('username',uesr.username, max_age=3600 * 24 * 14)


        return respones




class LoginView(View):

    def post(self,request):

        dict = json.loads(request.body.decode())

        # 提取
        username = dict.get('username')
        password = dict.get('password')
        remembered = dict.get('remembered')

        # 校验

        if not all([username,password]):
            return http.JsonResponse({"code": 400, "errmsg": "缺少参数"})

        # 验证 用户名和密码 用 Django 提供的authenticate  验证用户是否存在
        user = authenticate(request,username=username,password=password)

        # 存在 返回user 不存在返回none

        # 判断如果不存在 返回错误
        if user is None:
            return http.JsonResponse({"code": 400, "errmsg": "用户名或密码错误"})

        # 登录页面 我么也给用户做状态保持
        login(request,user)

        # 判断用户是否勾选记住密码 如果没有勾线 就退出删除保持
        if remembered != True:

            # 设置关闭立刻失效 设置的值为0
            request.session.set_expiry(0)

        else:
            # 设置记住的时间 None为默认有效时间
            request.session.set_expiry(None)



        # 有user 就响应成功  同时设置cookie 前端展示在首页
        respones = http.JsonResponse({"code": 0, "errmsg": "ok"})

        respones.set_cookie('username',user.username,max_age=3600 * 24 * 14)

        return respones


class LogoutView(View):

    def delete(self,request):

        # 清理 session  用django提供的 logout
        logout(request)

        # 也清除cookie 构建响应
        response = http.JsonResponse({'code': 0,  'errmsg':'ok'})

        response.delete_cookie('username')

        return response


# 首先继承我们自定义的类 用来检验用户是否登录

class UserInfoView(LoginRequiredMixin, View):

    def get(self,request):
        return http.JsonResponse({'code': 0,'errmsg': 'ok','info_data':{'username': request.user.username,
                'mobile': request.user.mobile,
                'email': request.user.email,
                'email_active': request.user.email_active
        }})







class EmailView(LoginRequiredMixin, View):

    def put(self, request):
        # 1、提取参数
        # b'{"email": '1@2.com'}'
        data_bytes = request.body
        # '{"email": '1@2.com'}'
        data_str = data_bytes.decode()
        # {"email": '1@2.com'}
        data = json.loads(data_str)

        email = data.get('email')

        # 2、校验参数
        if not email:
            return http.JsonResponse({'code': 400, 'errmsg': '缺失参数！'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱格式有误！'})

        # 3、更新用户email字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据库错误！'})

        # 4、发送验证邮件：邮件内容中包含一个链接，用户点击该链接完整验证
        # 针对不同的用户，生产不同的token。{"user_id": 1, "email": "1@2.com"}
        token = request.user.generate_token()
        verify_url = settings.EMAIL_VERIFY_URL + token

        # 发布任务函数
        send_verify_email.delay(email, verify_url)

        # 5、构建响应
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class VerifyEmailView(View):

    def put(self, request):

        # 1、提取验证请求中的查询字符串参数token
        token = request.GET.get('token')
        if not token:
            return http.JsonResponse({'code': 400, 'errmsg': 'token缺失！'})

        # 2、校验token值，获取用户身份
        user = User.check_token(token)
        if user is not None:
            # 2.1 验证成功，修改email_active参数为True
            user.email_active = True
            user.save()
            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})

        return http.JsonResponse({'code': 400, 'errmsg': '邮箱验证失败！'})


class CreateAddressView(View):

    def post(self,request):

        try:
        # 找用户设置默认地址的个数
            count = Address.objects.filter(user=request.user,is_deleted=False).count()
        # 地址超过个数就返回错误数据
        except Exception as e:
            return http.JsonResponse({'code': 400, 'errmsg': '获取地址数据出错'})

        # 判断
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '超过地址上线'})


        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})


        # 保存地址
        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 判断是否设置默认地址 没有就把当前的地址设置为默认地址

            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功,反应给前端

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code': 0,
                             'errmsg': '新增地址成功',
                             'address': address_dict})


class AddressView(View):
    def get(self,request):

        # 获取所有地址
        addresses = Address.objects.filter(user=request.user,is_deleted=False)

        # 遍历所有的地址
        address_dict_list = []

        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            default_address = request.user.default_address
            # 如果默认地址和设置的地址一样 就将它插入列表的开头  保持在前面
            if default_address.id == address.id:
                address_dict_list.insert(0,address_dict)

            # 如果不是 就加入地址列表
            else:
                address_dict_list.append(address_dict)

        # 设置默认地址

        default_id = request.user.default_address_id

        return http.JsonResponse({'code': 0,
                             'errmsg': 'ok',
                             'addresses': address_dict_list,
                             'default_address_id': default_id})


class UpdateDestroyAddressView(View):

    def put(self,request,address_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400,
                                 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400,
                                     'errmsg': '参数email有误'})

        # 判断地址是否存在 存在更新
        try:
            Address.objects.filter(id=address_id).update(
                 user=request.user,
                 title=receiver,
                 receiver=receiver,
                 province_id=province_id,
                 city_id=city_id,
                 district_id=district_id,
                 place=place,
                 mobile=mobile,
                 tel=tel,
                 email=email

             )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                 'errmsg': '更新地址失败'})

        # 根剧id查找地址id 构建响应
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return http.JsonResponse({'code': 0,
                             'errmsg': '更新地址成功',
                             'address': address_dict})




    def delete(self,request,address_id):
        # 查询要删除的地址

        try:
            address = Address.objects.get(id=address_id)

            # 讲逻辑删除设置为True
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                 'errmsg': '删除地址失败'})

        return http.JsonResponse({'code': 0,
                             'errmsg': '删除地址成功'})


class DefaultAddressView(View):
    def put(self,request,address_id):

        #查询地址
        try:
            address = Address.objects.get(id=address_id)

            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                 'errmsg': '设置默认地址失败'})


        return http.JsonResponse({'code': 0,
                             'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
        # 根据地址id查询地址
            address = Address.objects.get(id=address_id)

            address.title = title
            address.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                 'errmsg': '设置地址标题失败'})



        return http.JsonResponse({'code': 0,
                             'errmsg': '设置地址标题成功'})


class ChangePasswordView(LoginRequiredMixin, View):

    def put(self,request):
        dict = json.loads(request.body.decode())
        old_password = dict.get('old_password')
        new_password = dict.get('new_password')
        new_password2 = dict.get('new_password2')


        # 校验参数
        if not all([old_password, new_password, new_password2]):
           return http.JsonResponse({'code':400,
                                'errmsg':'缺少必传参数'})


        result = request.user.check_password(old_password)
        if not result:
            return http.JsonResponse({'code':400,
                                 'errmsg':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return http.JsonResponse({'code':400,
                                 'errmsg':'密码最少8位,最长20位'})

        if new_password != new_password2:
            return http.JsonResponse({'code':400,
                                 'errmsg':'两次输入密码不一致'})

        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                 'errmsg': '修改密码失败'})



        logout(request)

        response = http.JsonResponse({'code': 0,
                                 'errmsg': 'ok'})

        response.delete_cookie('username')

        # # 响应密码修改结果：重定向到登录界面
        return response






























































